package com.neurotech.pcc.other

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.Toast
import com.neurotech.pcc.R
import com.neurotech.pcc.dummy.RemoteModel
import com.shenhua.libs.sensocketcore.BaseClient
import com.shenhua.libs.sensocketcore.BaseMessageProcessor
import com.shenhua.libs.sensocketcore.IConnectListener
import com.shenhua.libs.sensocketcore.message.Message
import com.shenhua.libs.sensockettcp.TcpAddress
import com.shenhua.libs.sensockettcp.nio.TcpNioClient
import java.net.InetSocketAddress
import java.net.Socket
import java.util.*
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * Created by shenhua on 2019/1/28.
 * @author shenhua
 *         Email shenhuanet@126.com
 */
class RemoteClient(private var context: Context, private var remoteModel: RemoteModel) {

    private var tcpNioClient: TcpNioClient? = null
    private var executor: ExecutorService = Executors.newSingleThreadExecutor()

    private val mMessageProcessor = object : BaseMessageProcessor() {
        override fun onReceiveMessages(mClient: BaseClient, mQueen: LinkedList<Message>) {
            for (i in mQueen.indices) {
                Toast.makeText(context.applicationContext,
                        String.format(context.getString(R.string.text_has_shutdown_format),
                                remoteModel.host
                                        ?: ""), Toast.LENGTH_SHORT).show()
                tcpNioClient?.disconnect()
            }
        }
    }

    fun shutdown1() {
        Executors.newSingleThreadExecutor().execute {
            Log.d("shenhuaLog -- ${RemoteClient::class.java.simpleName}", "shutdown1: ${remoteModel.host}")
            try {
                val socket = Socket(remoteModel.host, 9)
                val out = socket.getOutputStream()
                out.write("shutdown".toByteArray())
                //out.close()
                //socket.close()
            } catch (e: Exception) {

            }
        }
    }

    fun shutdown() {
        val socketAddress = InetSocketAddress(remoteModel.host!!, 9)
        tcpNioClient = TcpNioClient(mMessageProcessor, object : IConnectListener {
            /**
             * 连接失败
             */
            override fun onConnectionFailed() {
                Handler(Looper.getMainLooper()).post {
                    Toast.makeText(context.applicationContext,
                            R.string.text_connect_failed, Toast.LENGTH_SHORT).show()
                }
            }

            /**
             * 连接成功
             */
            override fun onConnectionSuccess() {
                executor.execute {
                    mMessageProcessor.send(tcpNioClient!!, "shutdown".toByteArray())
                }
            }
        })
        tcpNioClient!!.setConnectAddress(arrayOf(TcpAddress(socketAddress.hostName, socketAddress.port)))
        tcpNioClient!!.connect()
    }

    fun destroy() {
        executor.shutdown()
        tcpNioClient = null
    }

}